package com.dongge.dao;

import com.dongge.entity.Role;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dongge.entity.User;
import java.util.List;
import java.util.Set;

/**
 * Created by zhudong on 2016/8/15.
 */
@Repository
public class RoleDao extends BaseDao{
    public List<Role> getRolesByUserId(long id){
        Session session = getSession();
        String hql = "select role from Role role,in (role.users) u where u.id =:id";
        return session.createQuery(hql).setLong("id",id).list();
    }

    public List<Role> getRoles(){
        Session session = getSession();
        String hql = "from Role";
        return session.createQuery(hql).list();
    }

    public long save(Role role){
        Session session = getSession();
        return (Long)session.save(role);
    }

    /**
     * 角色也不能同名
     * @param role
     */
    public int update(Role role){
        Session session = getSession();
        String hql = "update Role r set r.name = :name where "+
                "r.id=:id";
        return session.createQuery(hql).setString("name",role.getName())
            .setLong("id",role.getId())
            .executeUpdate();
    }

    public void addUser(Role role,User user){
        Session session = getSession();
        role.getUsers().add(user);
        session.saveOrUpdate(role);
    }

    public int delete(long id){
        Session session = getSession();
        String hql = "delete from Role r where r.id=:id";
        return session.createQuery(hql).setLong("id", id).executeUpdate();
    }
    /**
     * 如何添加一个元素到ManyToMany关系中
     */


    public Role get(long id){
        Session session = getSession();
        return (Role)session.get(Role.class,id);
    }


}
